package org.example.springboot.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.example.springboot.component.SseEmitterServer;
import org.example.springboot.entity.FmcControl;
import org.example.springboot.entity.PendingTasks;
import org.example.springboot.service.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class inTurnCheckHandler {

    @Resource
    private IrrigationUnitService irrigationUnitService;

    @Resource
    private FmcMetricsService fmcMetricsService;

    @Resource
    private MoistureControlService moistureControlService;

    @Resource
    private FmcControlService fmcControlService;

    @Resource
    private PendingTasksService pendingTasksService;

    @Resource
    private SseEmitterServer sseEmitterServer;

    @XxlJob("createInTurnCheckHandler")
    public void inTurnCheck(){
        PendingTasks pendingTasks = pendingTasksService.getOne(new QueryWrapper<PendingTasks>().select("sort").orderByAsc("sort").last("limit 1"));
        List<PendingTasks> pendingTasksList = pendingTasksService.list(new QueryWrapper<PendingTasks>().eq("sort", pendingTasks.getSort()));
            if(!pendingTasksList.isEmpty()){
                for(PendingTasks task : pendingTasksList){
                    String mqttContent = task.getMqttContent();
                    FmcControl fmcControl = JSON.parseObject(mqttContent, FmcControl.class);
                    log.info("轮灌溉MQTT消息 = {}", mqttContent);
                    fmcControlService.sendMessageToMqtt(fmcControl);
                    pendingTasksService.removeById(task);
                }
            }
        }
    }


